from asyncio import shield
from operator import truediv
import time
import json
import requests

from PyQt5.QtWidgets import QMainWindow
from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import QThread, pyqtSignal, Qt

from ui.counter import Ui_MainWindow

import RPi.GPIO as GPIO

from bases.config import *
from bases import globalvar
from bases.player import SoundPlayer
from libs.counter import ImageCounter
from libs.qrcode import Qrcode
from libs.ioctrl import IoCtrl

'''
    计数器 计数业务代码写到这里
'''


class CounterWindow(QMainWindow):
    changeNumSignal = pyqtSignal(int)
    changeInfoSignal = pyqtSignal(str)

    # 二维码解析结果的缓存
    jsondict = {}

    def __init__(self):
        QMainWindow.__init__(self)  # QMainWindow的初始化
        self.main_ui = Ui_MainWindow()  # 主窗口的实例化
        self.main_ui.setupUi(self)

        '''
            多线程下，其他线程无法直接更新UI线程，需要用pyqt的信号(signal)
        '''
        self.delayThread = UiDelay()
        self.delayThread.timeoutSignal.connect(self.delayClear)

        self.http = NetReqeust()

        self.changeNumSignal.connect(self.changeNumberCallback)
        self.changeInfoSignal.connect(self.changeInfomationCallback)

        self.delayThread.start()

    def cb_func_counter(self, sa):

        GPIO.remove_event_detect(Din2)
        count = ImageCounter.capAndAnalysis()
        self.changeNumber(count)
        SoundPlayer.play(count)
        print("\n GPIO: Rising Edge Detected.Sending message to DingTalk.")

    def showEvent(self, event: QtGui.QShowEvent):
        # 显示后注册监听事件
        # GPIO.add_event_detect(Din2, GPIO.FALLING)  ##注册一个检测电压由低变高事件
        # GPIO.add_event_callback(Din2, self.cb_func_counter, bouncetime=200)  ##检测到事件触发回调getRespose 函数
        GPIO.add_event_detect(Din2, GPIO.RISING, callback=self.cb_func_counter, bouncetime=200)
        print('add din2 interrupt event')

    def closeEvent(self, a0: QtGui.QCloseEvent):
        # 窗口关闭时取消注册中断监听，避免误操作
        GPIO.remove_event_detect(Din2)
        print('removed din2 interrupt event')

    '''
        延迟清空考场与计数
    '''

    def delayClear(self):
        # self.main_ui.infomation.setText("")
        self.main_ui.number.setText("")

    '''
        数据传递
    '''

    def dataPass(self, data):
        self.main_ui.infomation.setText(data)

    def dataPass2(self, data):
        self.main_ui.infomation_area.setText(data)

    '''
        更新显示计数值
    '''

    def changeNumber(self, num):
        self.changeNumSignal.emit(num)
        self.jsondict['checkNum'] = num
        self.http.post(self.jsondict)

    def changeNumberCallback(self, num):
        _translate = QtCore.QCoreApplication.translate
        self.main_ui.number.setText(_translate("MainWindow",
                                               "<html><head/><body><p align=\"center\">" + str(
                                                   num) + "</p></body></html>"))
        # 标记可以继续 按下 开关计数了
        GPIO.add_event_detect(Din2, GPIO.RISING, callback=self.cb_func_counter, bouncetime=200)

        self.delayThread.start()

    '''
        扫描二维码后更新考察信息显示
    '''

    def changeInfomation(self, jsonStr):
        try:
            jsonmap = json.loads(jsonStr)
        except json.decoder.JSONDecodeError as e:
            self.changeInfoSignal.emit('无法识别的二维码')
            self.delayThread.start()
            return

        self.jsondict = jsonmap
        self.changeInfoSignal.emit(jsonmap['code'] + ' - ' + jsonmap['subject'])

    def changeInfomationCallback(self, txt):
        _translate = QtCore.QCoreApplication.translate
        self.main_ui.infomation.setText(_translate("MainWindow",
                                                   "<html><head/><body><p align=\"center\">" + txt + "</p></body></html>"))

    def keyPressEvent(self, event: QtGui.QKeyEvent):
        print("按下：" + str(event.key()))
        # 退出键定义
        if (event.key() == Qt.Key_Escape):
            self.close()
            print('测试：退出')
        # 计数键定义
        if (event.key() == 16777220):
            sa = None
            self.cb_func_counter(sa)
            # count = ImageCounter.capAndAnalysis()
            # self.changeNumber(count)
            # SoundPlayer.play(count)
            print('测试：计数')
        # 二维码功能调用
        if (event.key() == Qt.Key_0):
            print('测试：0')
            brs = Qrcode.detect()
            if (brs is not None):
                self.changeInfomation(brs[0])
        if (event.key() == Qt.Key_1):
            print('测试：1')
        if (event.key() == Qt.Key_2):
            print('测试：2')
        if (event.key() == Qt.Key_3):
            print('测试：3')
        if (event.key() == Qt.Key_4):
            print('测试：4')
        if (event.key() == Qt.Key_5):
            print('测试：5')
        if (event.key() == Qt.Key_6):
            print('测试：6')
        if (event.key() == Qt.Key_7):
            print('测试：7')
        if (event.key() == Qt.Key_8):
            print('测试：8')
        if (event.key() == Qt.Key_9):
            print('测试：9')


'''
    UI 后台线程, 延迟清空显示的内容
'''


class UiDelay(QThread):
    # 定义信号,定义参数为str类型
    timeoutSignal = pyqtSignal()

    def __init__(self, parent=None):
        super().__init__(parent)

        # 下面的初始化方法都可以，有的python版本不支持
        # super(Mythread, self).__init__()

    def run(self):
        time.sleep(4)
        self.timeoutSignal.emit()


# REQUEST_URL = "http://xhsaas.com/answer-sheet/api/client/checkNum" #测试接口
REQUEST_URL = "http://maozz.imwork.net:8081/prod-api/exam/bigScreen/pushData"  # 推数据接口
ERRORCORRECTION_URL = "http://maozz.imwork.net:8081/prod-api/exam/bigScreen/errorCorrection"  # 数据纠错接口
HEADER = {'Content-Type': 'application/json; charset=utf-8'}

'''
   网络请求线程，UI线程可能不允许进行网络请求（阻塞UI更新）
'''


class NetReqeust(QThread):
    # 定义信号,定义参数为str类型
    requestSignal = pyqtSignal(int)

    pushBody = {
        "areaCode": "1",
        "pointCode": "1",
        "roomCode": "1",
        "subjectCode": "1",
        "projectCode": "1",
        "cardCount": "1"
    }
    errorCorrectionBody = {
        "areaCode": "1",
        "pointCode": "1",
        "roomCode": "1"
    }

    def __init__(self, parent=None):
        super().__init__(parent)

        # 下面的初始化方法都可以，有的python版本不支持
        # super(Mythread, self).__init__()

    def post(self, body):
        self.pushBody = body
        self.start()

    def run(self):
        self.requestSignal.emit(1)
        rsp = requests.post(REQUEST_URL, data=json.dumps(self.pushBody), headers=HEADER)
        rsp_ec = requests.post(ERRORCORRECTION_URL, data=json.dumps(self.errorCorrectionBody), headers=HEADER)
        print(rsp)
        print(rsp_ec)
        # if rsp.status_code == 200:
        #     return True
        # else:
        #     return False
        self.requestSignal.emit(2)
